//
//  GNRAlertManager.m
//  app
//
//  Created by LvYuan on 16/9/30.
//  Copyright © 2016年 UU. All rights reserved.
//

#import "GNRAlertManager.h"
#import "GNRAlertView.h"

static GNRAlertManager * manager;

@interface GNRAlertManager()



@end

@implementation GNRAlertManager

+ (void)setDefaultStyle:(GNRAlertStyle)style{
    [GNRAlertManager manager].defaultStyle = style;
}

+ (void)setDefaultIconImage:(UIImage *)defaultIconImage{
    [GNRAlertManager manager].defaultIconImage = defaultIconImage;
}

+ (void)setDefaultHeaderBgImage:(UIImage *)defaultHeaderBgImage{
    [GNRAlertManager manager].defaultHeaderBgImage = defaultHeaderBgImage;
}

- (NSMutableArray *)alerts{
    if (!_alerts) {
        _alerts = [NSMutableArray array];
    }
    return _alerts;
}

+ (GNRAlertManager *)manager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (void)addAlertView:(GNRAlertView *)alertView{
    if (alertView) {
        
        BOOL hasSameAlert = [self hasSameAlert:alertView];
        
        if (hasSameAlert) {//有相同的标识
            [alertView gnr_hidden:YES];
            [alertView dismiss];
            return;
        }
        
        [self.alerts addObject:alertView];
        [self.alerts enumerateObjectsUsingBlock:^(GNRAlertView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            //非我皆暂时隐藏
            if ( obj) {
                if (obj != alertView) {
                    [obj gnr_hidden:YES];
                }
            }
        }];
    }
}
- (void)addNewAlertView:(GNRAlertView *)alertView{
    if (alertView) {
        
        BOOL hasSameAlert = [self hasSameAlert:alertView];
        if (hasSameAlert) {//有相同的标识
            [alertView gnrNew_hidden:YES];
            [alertView dismissWindow];
            return;
        }
        
        [self.alerts addObject:alertView];
        [self.alerts enumerateObjectsUsingBlock:^(GNRAlertView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            //非我皆暂时隐藏
            if ( obj) {
                if (obj != alertView) {
                    [obj gnrNew_hidden:YES];
                }
            }
        }];
    }
}


//是否已经存在该类型弹窗
- (BOOL)hasSameAlert:(GNRAlertView *)alertView{
    for (GNRAlertView *alert in self.alerts) {
        if (alertView.identifier.length&&
            [alertView.identifier isEqualToString:alert.identifier]) {
            return YES;
        }
    }
    return NO;
}

- (void)removeAlertView:(GNRAlertView *)alertView{
    [self.alerts removeObject:alertView];
    if (self.alerts.count) {//最上层显示
        [self.alerts.lastObject gnr_hidden:NO];
    }
}

@end
